<template>
  <view class="bookshelf-container">
    <!-- 头部 -->
    <view class="bookshelf-header">
      <text class="header-title">我的书架</text>
      <view class="header-actions">
        <text class="action-btn" @click="toggleEditMode">
          {{ isEditMode ? '完成' : '编辑' }}
        </text>
        <text class="action-btn" @click="showSortModal">排序</text>
      </view>
    </view>

    <!-- 空状态 -->
    <view v-if="books.length === 0" class="empty-bookshelf">
      <image src="/static/empty-bookshelf.png" class="empty-image" mode="aspectFit" />
      <text class="empty-text">书架空空如也</text>
      <text class="empty-desc">快去书城添加喜欢的书籍吧</text>
      <button class="go-bookstore-btn" @click="goToBookStore">去书城逛逛</button>
    </view>

    <!-- 书架内容 -->
    <scroll-view 
      v-else 
      scroll-y 
      class="bookshelf-content" 
      :style="{ height: scrollViewHeight + 'px' }"
      @refresherrefresh="onRefresh" 
      refresher-enabled
    >
      <!-- 书架统计 -->
      <view class="bookshelf-stats">
        <view class="stat-item">
          <text class="stat-number">{{ books.length }}</text>
          <text class="stat-label">本书籍</text>
        </view>
        <view class="stat-item">
          <text class="stat-number">{{ readingCount }}</text>
          <text class="stat-label">在读</text>
        </view>
        <view class="stat-item">
          <text class="stat-number">{{ finishedCount }}</text>
          <text class="stat-label">已读</text>
        </view>
        <view class="stat-item">
          <text class="stat-number">{{ totalReadingTime }}</text>
          <text class="stat-label">阅读时长</text>
        </view>
      </view>

      <!-- 书架网格 -->
      <view class="books-grid">
        <view 
          v-for="book in sortedBooks" 
          :key="book.id"
          class="book-item"
          @click="goToBookDetail(book)"
        >
          <view class="book-cover-container">
            <image :src="book.cover" class="book-cover" mode="aspectFill" />
            <!-- 阅读进度 -->
            <view v-if="book.progress > 0" class="reading-progress">
              <view 
                class="progress-bar" 
                :style="{ width: book.progress + '%' }"
              ></view>
            </view>
            <!-- 阅读状态标签 -->
            <view class="book-status" :class="book.status">
              {{ getStatusText(book.status) }}
            </view>
            <!-- 编辑模式选择框 -->
            <view v-if="isEditMode" class="selection-checkbox">
              <checkbox 
                :checked="selectedBooks.includes(book.id)" 
                @click.stop="toggleSelectBook(book.id)"
              />
            </view>
          </view>
          
          <view class="book-info">
            <text class="book-title">{{ book.title }}</text>
            <text class="book-author">{{ book.author }}</text>
            <view class="book-meta">
              <text class="book-progress" v-if="book.progress > 0">
                已读{{ book.progress }}%
              </text>
              <text class="book-update" v-if="book.lastReadTime">
                {{ formatTime(book.lastReadTime) }}
              </text>
            </view>
          </view>
        </view>
      </view>

      <!-- 加载更多 -->
      <view v-if="hasMore" class="load-more" @click="loadMore">
        <text class="load-more-text">加载更多</text>
      </view>
      
      <!-- 底部占位区域 -->
      <view class="bottom-placeholder" :style="{ height: placeholderHeight + 'px' }"></view>
    </scroll-view>

    <!-- 编辑模式底部操作栏 -->
    <view v-if="isEditMode && books.length > 0" class="edit-toolbar">
      <view class="toolbar-left">
        <checkbox 
          :checked="isAllSelected" 
          @click="toggleSelectAll"
          class="select-all-checkbox"
        />
        <text class="select-all-text">全选</text>
        <text class="selected-count">已选{{ selectedBooks.length }}本</text>
      </view>
      <view class="toolbar-actions">
        <text class="toolbar-btn delete" @click="batchDelete">删除</text>
        <text class="toolbar-btn move" @click="showMoveModal">移动到</text>
      </view>
    </view>

    <!-- 排序弹窗 -->
    <view v-if="showSortPanel" class="sort-modal" @click="hideSortModal">
      <view class="sort-content" @click.stop>
        <view class="sort-header">
          <text class="sort-title">排序方式</text>
          <text class="sort-close" @click="hideSortModal">×</text>
        </view>
        <view class="sort-options">
          <view 
            v-for="option in sortOptions" 
            :key="option.value"
            class="sort-option"
            :class="{ active: sortBy === option.value }"
            @click="changeSort(option.value)"
          >
            <text class="option-text">{{ option.label }}</text>
            <text v-if="sortBy === option.value" class="option-check">✓</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 分类移动弹窗 -->
    <view v-if="showMovePanel" class="move-modal" @click="hideMoveModal">
      <view class="move-content" @click.stop>
        <view class="move-header">
          <text class="move-title">移动到分类</text>
          <text class="move-close" @click="hideMoveModal">×</text>
        </view>
        <view class="category-list">
          <view 
            v-for="category in categories" 
            :key="category.id"
            class="category-item"
            @click="moveToCategory(category.id)"
          >
            <text class="category-name">{{ category.name }}</text>
            <text class="category-count">{{ category.bookCount }}本</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部导航栏 -->
    <view class="tab-bar">
      <view 
        v-for="tab in tabList" 
        :key="tab.pagePath"
        class="tab-item"
        :class="{ active: currentTab === tab.pagePath }"
        @click="switchTab(tab)"
      >
        <view class="tab-icon">
          <image 
            :src="currentTab === tab.pagePath ? tab.selectedIconPath : tab.iconPath" 
            class="icon"
            mode="aspectFit"
          />
          <!-- 书架角标 -->
          <view v-if="tab.pagePath === 'bookshelf' && unreadCount > 0" class="bookshelf-badge">
            <text class="badge-text">{{ unreadCount > 99 ? '99+' : unreadCount }}</text>
          </view>
        </view>
        <text class="tab-text">{{ tab.text }}</text>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      books: [],
      selectedBooks: [],
      isEditMode: false,
      showSortPanel: false,
      showMovePanel: false,
      sortBy: 'time',
      currentPage: 1,
      pageSize: 20,
      hasMore: true,
      scrollViewHeight: 0,
      placeholderHeight: 0,
      currentTab: 'bookshelf',
      unreadCount: 0,
      categories: [
        { id: 1, name: '默认书架', bookCount: 0 },
        { id: 2, name: '正在阅读', bookCount: 0 },
        { id: 3, name: '已读完', bookCount: 0 },
        { id: 4, name: '想读', bookCount: 0 }
      ],
      sortOptions: [
        { value: 'time', label: '最近阅读' },
        { value: 'add', label: '添加时间' },
        { value: 'name', label: '书名排序' },
        { value: 'progress', label: '阅读进度' }
      ],
      tabList: [
        {
          pagePath: 'index',
          text: '首页',
          iconPath: '/static/tabbar/home.png',
          selectedIconPath: '/static/tabbar/home-active.png'
        },
        {
          pagePath: 'category',
          text: '分类',
          iconPath: '/static/tabbar/category.png',
          selectedIconPath: '/static/tabbar/category-active.png'
        },
        {
          pagePath: 'bookshelf',
          text: '书架',
          iconPath: '/static/tabbar/bookshelf.png',
          selectedIconPath: '/static/tabbar/bookshelf-active.png'
        },
        {
          pagePath: 'profile',
          text: '我的',
          iconPath: '/static/tabbar/profile.png',
          selectedIconPath: '/static/tabbar/profile-active.png'
        }
      ]
    }
  },
  computed: {
    readingCount() {
      return this.books.filter(book => book.status === 'reading').length
    },
    finishedCount() {
      return this.books.filter(book => book.status === 'finished').length
    },
    totalReadingTime() {
      const totalMinutes = this.books.reduce((sum, book) => sum + (book.readingTime || 0), 0)
      return totalMinutes > 60 ? `${Math.floor(totalMinutes / 60)}小时` : `${totalMinutes}分钟`
    },
    sortedBooks() {
      const books = [...this.books]
      switch (this.sortBy) {
        case 'time':
          return books.sort((a, b) => new Date(b.lastReadTime) - new Date(a.lastReadTime))
        case 'add':
          return books.sort((a, b) => new Date(b.addTime) - new Date(a.addTime))
        case 'name':
          return books.sort((a, b) => a.title.localeCompare(b.title))
        case 'progress':
          return books.sort((a, b) => b.progress - a.progress)
        default:
          return books
      }
    },
    isAllSelected() {
      return this.selectedBooks.length === this.books.length && this.books.length > 0
    }
  },
  onLoad() {
    this.calcLayoutHeight()
    this.loadBookshelf()
    this.updateUnreadCount()
  },
  onShow() {
    this.updateUnreadCount()
  },
  onPullDownRefresh() {
    this.refreshBookshelf().finally(() => {
      uni.stopPullDownRefresh()
    })
  },
  onResize() {
    this.calcLayoutHeight()
  },
  methods: {
    // 计算布局高度
    calcLayoutHeight() {
      const systemInfo = uni.getSystemInfoSync()
      const windowHeight = systemInfo.windowHeight
      const tabBarHeight = 100 // 底部导航栏高度
      const headerHeight = 120 // 头部高度
      
      // 内容区域高度 = 窗口高度 - 头部高度 - 底部导航栏高度
      this.scrollViewHeight = windowHeight - headerHeight - tabBarHeight
      
      // 占位区域高度 = 底部导航栏高度 + 安全区域底部间距
      this.placeholderHeight = tabBarHeight + (systemInfo.safeAreaInsets?.bottom || 0)
    },
    
    async loadBookshelf() {
      try {
        uni.showLoading({ title: '加载中...' })
        
        // 先从本地存储加载，如果没有则生成模拟数据
        let bookshelf = uni.getStorageSync('bookshelf')
        if (!bookshelf || bookshelf.length === 0) {
          bookshelf = this.generateMockBooks()
          uni.setStorageSync('bookshelf', bookshelf)
        }
        
        this.books = bookshelf
        this.hasMore = false // 本地数据不需要分页
        
      } catch (error) {
        console.error('加载书架失败:', error)
        uni.showToast({ title: '加载失败', icon: 'none' })
      } finally {
        uni.hideLoading()
      }
    },

    async refreshBookshelf() {
      await this.loadBookshelf()
    },

    async loadMore() {
      // 本地数据不需要加载更多
    },

    generateMockBooks() {
      const bookTitles = [
        '三体', '百年孤独', '活着', '围城', '平凡的世界', 
        '红楼梦', '西游记', '水浒传', '三国演义', '时间简史'
      ]
      
      const authors = ['刘慈欣', '马尔克斯', '余华', '钱钟书', '路遥', '曹雪芹', '吴承恩', '施耐庵', '罗贯中', '霍金']
      
      return Array.from({ length: 8 }, (_, i) => {
        const statuses = ['unread', 'reading', 'finished']
        const status = statuses[Math.floor(Math.random() * statuses.length)]
        const progress = status === 'unread' ? 0 : 
                        status === 'reading' ? Math.floor(Math.random() * 90) + 10 : 
                        100
        
        return {
          id: i + 1,
          title: bookTitles[i % bookTitles.length],
          author: authors[i % authors.length],
          cover: `/static/book${(i % 8) + 1}.jpg`,
          status: status,
          progress: progress,
          readingTime: Math.floor(Math.random() * 300) + 10,
          lastReadTime: new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000).toISOString(),
          addTime: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString(),
          category: 1
        }
      })
    },

    toggleEditMode() {
      this.isEditMode = !this.isEditMode
      if (!this.isEditMode) {
        this.selectedBooks = []
      }
    },

    toggleSelectBook(bookId) {
      const index = this.selectedBooks.indexOf(bookId)
      if (index > -1) {
        this.selectedBooks.splice(index, 1)
      } else {
        this.selectedBooks.push(bookId)
      }
    },

    toggleSelectAll() {
      if (this.isAllSelected) {
        this.selectedBooks = []
      } else {
        this.selectedBooks = this.books.map(book => book.id)
      }
    },

    batchDelete() {
      if (this.selectedBooks.length === 0) {
        uni.showToast({ title: '请选择要删除的书籍', icon: 'none' })
        return
      }

      uni.showModal({
        title: '确认删除',
        content: `确定要删除选中的 ${this.selectedBooks.length} 本书籍吗？`,
        confirmColor: '#ff6b6b',
        success: (res) => {
          if (res.confirm) {
            this.books = this.books.filter(book => !this.selectedBooks.includes(book.id))
            uni.setStorageSync('bookshelf', this.books)
            this.selectedBooks = []
            this.updateUnreadCount()
            uni.showToast({ title: '删除成功', icon: 'success' })
            
            if (this.books.length === 0) {
              this.isEditMode = false
            }
          }
        }
      })
    },

    showSortModal() {
      this.showSortPanel = true
    },

    hideSortModal() {
      this.showSortPanel = false
    },

    changeSort(sortType) {
      this.sortBy = sortType
      this.hideSortModal()
    },

    showMoveModal() {
      if (this.selectedBooks.length === 0) {
        uni.showToast({ title: '请选择要移动的书籍', icon: 'none' })
        return
      }
      this.showMovePanel = true
    },

    hideMoveModal() {
      this.showMovePanel = false
    },

    moveToCategory(categoryId) {
      this.books.forEach(book => {
        if (this.selectedBooks.includes(book.id)) {
          book.category = categoryId
        }
      })
      uni.setStorageSync('bookshelf', this.books)
      uni.showToast({ title: '移动成功', icon: 'success' })
      this.selectedBooks = []
      this.hideMoveModal()
      this.isEditMode = false
    },

    goToBookDetail(book) {
      if (this.isEditMode) return
      
      uni.navigateTo({
        url: `/pages/reader/reader?id=${book.id}`
      })
    },

    goToBookStore() {
      uni.switchTab({
        url: '/pages/category/category'
      })
    },

    getStatusText(status) {
      const statusMap = {
        unread: '未读',
        reading: '阅读中',
        finished: '已读完'
      }
      return statusMap[status] || '未读'
    },

    formatTime(timeStr) {
      const time = new Date(timeStr)
      const now = new Date()
      const diff = now - time
      const days = Math.floor(diff / (1000 * 60 * 60 * 24))
      
      if (days === 0) return '今天'
      if (days === 1) return '昨天'
      if (days < 7) return `${days}天前`
      if (days < 30) return `${Math.floor(days / 7)}周前`
      return `${Math.floor(days / 30)}月前`
    },

    updateUnreadCount() {
      this.unreadCount = this.books.filter(book => book.status === 'unread').length
    },

    switchTab(tab) {
      if (this.currentTab === tab.pagePath) return
      
      const pageMap = {
        'index': '/pages/index/index',
        'category': '/pages/category/category',
        'bookshelf': '/pages/bookshelf/bookshelf',
        'profile': '/pages/profile/profile'
      }
      
      const targetUrl = pageMap[tab.pagePath]
      if (targetUrl) {
        uni.switchTab({
          url: targetUrl,
          fail: (err) => {
            console.error('跳转失败:', err)
            uni.redirectTo({
              url: targetUrl
            })
          }
        })
      }
    },

    onRefresh() {
      this.refreshBookshelf()
    }
  }
}
</script>

<style lang="scss" scoped>
.bookshelf-container {
  height: 100vh;
  background: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.bookshelf-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  background: #fff;
  border-bottom: 1rpx solid #f0f0f0;
  position: sticky;
  top: 0;
  z-index: 10;
  height: 120rpx;
  box-sizing: border-box;
}

.header-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 30rpx;
}

.action-btn {
  font-size: 28rpx;
  color: #007AFF;
}

.empty-bookshelf {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding-bottom: 200rpx;
}

.empty-image {
  width: 300rpx;
  height: 300rpx;
  margin-bottom: 40rpx;
  opacity: 0.6;
}

.empty-text {
  font-size: 32rpx;
  color: #666;
  margin-bottom: 20rpx;
}

.empty-desc {
  font-size: 26rpx;
  color: #999;
  margin-bottom: 50rpx;
}

.go-bookstore-btn {
  background: #007AFF;
  color: #fff;
  height: 80rpx;
  line-height: 80rpx;
  border-radius: 40rpx;
  padding: 0 60rpx;
  font-size: 28rpx;
  border: none;
}

.bookshelf-content {
  flex: 1;
  padding: 20rpx;
}

.bookshelf-stats {
  display: flex;
  background: #fff;
  border-radius: 15rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
}

.stat-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stat-number {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
}

.stat-label {
  font-size: 24rpx;
  color: #666;
}

.books-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20rpx;
}

.book-item {
  background: #fff;
  border-radius: 12rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.06);
}

.book-cover-container {
  position: relative;
  width: 100%;
  padding-top: 140%;
  background: #f5f5f5;
}

.book-cover {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: block;
}

.reading-progress {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 6rpx;
  background: rgba(0,0,0,0.1);
}

.progress-bar {
  height: 100%;
  background: #007AFF;
  transition: width 0.3s ease;
}

.book-status {
  position: absolute;
  top: 10rpx;
  right: 10rpx;
  padding: 6rpx 12rpx;
  border-radius: 12rpx;
  font-size: 20rpx;
  color: #fff;
  line-height: 1;
}

.book-status.unread {
  background: rgba(0,0,0,0.6);
}

.book-status.reading {
  background: #007AFF;
}

.book-status.finished {
  background: #4CD964;
}

.selection-checkbox {
  position: absolute;
  top: 10rpx;
  left: 10rpx;
  z-index: 2;
}

.book-info {
  padding: 20rpx;
}

.book-title {
  display: block;
  font-size: 26rpx;
  font-weight: 600;
  color: #333;
  line-height: 1.4;
  margin-bottom: 8rpx;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  min-height: 72rpx;
}

.book-author {
  display: block;
  font-size: 22rpx;
  color: #666;
  margin-bottom: 12rpx;
}

.book-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.book-progress, .book-update {
  font-size: 20rpx;
  color: #999;
}

.load-more {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40rpx 0;
}

.load-more-text {
  font-size: 28rpx;
  color: #007AFF;
}

.bottom-placeholder {
  width: 100%;
}

.edit-toolbar {
  position: fixed;
  bottom: 100rpx;
  left: 0;
  right: 0;
  height: 100rpx;
  background: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 30rpx;
  border-top: 1rpx solid #f0f0f0;
  box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.1);
  z-index: 99;
}

.toolbar-left {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.select-all-checkbox {
  margin-right: 10rpx;
}

.select-all-text {
  font-size: 28rpx;
  color: #333;
}

.selected-count {
  font-size: 24rpx;
  color: #666;
  margin-left: 10rpx;
}

.toolbar-actions {
  display: flex;
  gap: 30rpx;
}

.toolbar-btn {
  padding: 16rpx 30rpx;
  border-radius: 20rpx;
  font-size: 26rpx;
  font-weight: 600;
  border: none;
}

.toolbar-btn.delete {
  background: #ff6b6b;
  color: #fff;
}

.toolbar-btn.move {
  background: #007AFF;
  color: #fff;
}

/* 弹窗样式 */
.sort-modal, .move-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  align-items: flex-end;
  z-index: 1000;
}

.sort-content, .move-content {
  background: #fff;
  border-radius: 30rpx 30rpx 0 0;
  width: 100%;
  max-height: 60vh;
}

.sort-header, .move-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.sort-title, .move-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.sort-close, .move-close {
  font-size: 40rpx;
  color: #999;
}

.sort-options {
  padding: 20rpx 0;
}

.sort-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f8f8f8;
}

.sort-option.active {
  color: #007AFF;
}

.option-text {
  font-size: 28rpx;
}

.option-check {
  color: #007AFF;
  font-size: 28rpx;
}

.category-list {
  padding: 20rpx 0;
  max-height: 40vh;
  overflow-y: auto;
}

.category-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f8f8f8;
}

.category-name {
  font-size: 28rpx;
  color: #333;
}

.category-count {
  font-size: 24rpx;
  color: #999;
}

/* 底部导航栏样式 */
.tab-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  background: #fff;
  border-top: 1rpx solid #f0f0f0;
  padding-bottom: env(safe-area-inset-bottom);
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  display: flex;
  align-items: center;
  z-index: 999;
}

.tab-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  position: relative;
  
  &.active {
    .tab-text {
      color: #ff6b6b;
    }
  }
}

.tab-icon {
  position: relative;
  margin-bottom: 8rpx;
}

.icon {
  width: 44rpx;
  height: 44rpx;
  display: block;
}

.bookshelf-badge {
  position: absolute;
  top: -10rpx;
  right: -10rpx;
  background: #ff6b6b;
  border-radius: 20rpx;
  min-width: 30rpx;
  height: 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 8rpx;
}

.badge-text {
  color: #fff;
  font-size: 20rpx;
  line-height: 1;
}

.tab-text {
  font-size: 22rpx;
  color: #666;
}
</style>
